import Crypt from "../../../utils/Crypt";
import UserModel from "../../../models/User";

const userModel = new UserModel()

Page({
  data: {
    isExist: false,
    oldPassword: '',
    password1: '',
    password2: '',
  },
  onLoad: function (options) {
    userModel.checkPayPassword().then(response => {
      let { data } = response
      data = Crypt.parse(data)
      this.setData({ isExist: data.result })
    })
    // this.setData({
    //   oldPassword: '',
    //   password1: '',
    //   password2: '',
    // })
  },

  bindOldPassword(e) {
    this.setData({ oldPassword: e.detail.value })
  },

  bindPassword1(e) {
    this.setData({ password1: e.detail.value })
  },

  bindPassword2(e) {
    this.setData({ password2: e.detail.value })
  },

  onSave() {
    if (this.data.isExist) {
      if (!this.data.oldPassword) {
        return wx.showToast({title: '请输入旧密码', icon: 'error'})
      }
    }
    if (!this.data.password1) {
      return wx.showToast({title: '请输入新密码', icon: 'error'})
    }
    if (!this.data.password2) {
      return wx.showToast({title: '请输入重复密码', icon: 'error'})
    }
    if (this.data.password1 != this.data.password2) {
      return wx.showToast({title: '两次密码不一致', icon: 'error'})
    }
    if (this.data.password1.length < 6) {
      return wx.showToast({title: '密码长度不能小于6位', icon: 'error'})
    }

    // save
    userModel.editPayPassword({ ...this.data, old_password: this.data.oldPassword }).then(() => {
      wx.showModal({title: '保存成功', success: () => {
        wx.switchTab({
          url: '/pages/center/index'
        })
      }})
    })
  }
});
